<template>
  <div>
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
        required
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="验证码"
        :rules="rules.code"
        required
      />
      <div style="margin: 16px;">
        <van-button round block :disabled="isLoading" :loading="isLoading" loading-text="登录中..." type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'login',
  data () {
    return {
      mobile: '13912345678',
      code: '246810',
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/
          }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login () {
      this.isLoading = true
      try {
        const res = await login(this.mobile, this.code)
        // console.log(res)
        this.setToken(res.data)
        // await this.$store.dispatch('user/login', {
        //   mobile: this.mobile,
        //   code: this.code
        // })
        // alert('登录成功')
        // localStorage.setItem('heima-news-83', JSON.stringify(res.data))
        this.$toast.success('登录成功')
        if (this.$route.query.goBack) {
          this.$router.back()
          return
        }
        const back = this.$route.query.back || '/'
        this.$router.push(back)
      } catch {
        this.$toast.fail('用户名或者验证码错误')
        // alert('用户名或者验证码错误')
      }
      this.isLoading = false
    }
  }
}
</script>

<style>

</style>
